//
//  HJChatMessageModel.m
//  KaiChat
//
//  Created by lx on 2023/10/21.
//

#import "HJChatMessageModel.h"
#import "HJWebsiteFillter.h"

@implementation HJChatMessageModel


MJLogAllIvars

+ (NSArray *)bg_uniqueKeys {
    return @[@"msgId"];
}

+ (NSArray *)bg_ignoreKeys {
    return @[
        @"thumbnailImage", @"thumbs",
        @"asset", @"originalImage", @"fileURL",
        @"isForword", @"lastMessageTime", @"totalUnitCount",
        @"countedUnreadCount", @"isRetry", @"userInfoChange"
    ];
}

+(NSArray *)mj_ignoredPropertyNames {
    return [self bg_ignoreKeys];
}

- (NSString *)bg_tableName {
    return [NSString stringWithFormat:@"%@_%@", NSStringFromClass(self.class), [NSString stringWithFormat:@"%@%@", HJUserInfo.userId, _sessionId].md5];
}

+ (NSString *)bg_tableNameWithSessionId:(NSString *)sessionId {
    return [NSString stringWithFormat:@"%@_%@", NSStringFromClass(self.class), [NSString stringWithFormat:@"%@%@", HJUserInfo.userId, sessionId].md5];
}

//根据收到的消息构造消息模型, 收到消息拿用户Id去查询用户信息

+ (HJChatMessageModel *)newsMessageModelWithDict:(NSDictionary *)dict {
    HJChatMessageModel *messageModel = [HJChatMessageModel baseMessageModelWithDict:dict];
    messageModel.senderId = toString(dict[@"send_uid"]);
    messageModel.officialType = HJChatOfficialTypeKaiNews;
    messageModel.sessionId = getOfficiaSessionId(dict[@"session_id"]);
    messageModel.receiverId = HJUserInfo.userId;
    messageModel.senderNickname = dict[@"sender_name"];
    messageModel.senderAvatar = dict[@"sender_pic"];
    messageModel.sessionName = messageModel.senderNickname;
    messageModel.sessionAvatar = messageModel.senderAvatar;
    messageModel.associationmMsgId = toString(dict[@"association_msg_id"]);
    NSDictionary *msgDict = dict[@"msg"];
    NSDictionary *contentDict = [msgDict[@"content"] mj_JSONObject];
    messageModel.content = contentDict[@"title"];
    messageModel.msg = [@{
        @"content": contentDict
    } mj_JSONString];
    return messageModel;
}

+ (HJChatMessageModel *)payMessageModelWithDict:(NSDictionary *)dict {
    
    HJChatMessageModel *messageModel = [HJChatMessageModel baseMessageModelWithDict:dict];
    messageModel.senderId = toString(dict[@"send_uid"]);
    messageModel.officialType = HJChatOfficialTypeKaiPay;
    messageModel.sessionId = getOfficiaSessionId(dict[@"session_id"]);
    messageModel.receiverId = HJUserInfo.userId;
    messageModel.senderNickname = dict[@"sender_name"];
    messageModel.senderAvatar = dict[@"sender_pic"];
    messageModel.sessionName = messageModel.senderNickname;
    messageModel.sessionAvatar = messageModel.senderAvatar;
    messageModel.associationmMsgId = toString(dict[@"association_msg_id"]);
    NSDictionary *msgDict = dict[@"msg"];
    NSDictionary *contentDict = [msgDict[@"content"] mj_JSONObject];
    messageModel.content = contentDict[@"title"];
    messageModel.msg = [@{
        @"content": contentDict
    } mj_JSONString];
    return messageModel;
}

//不保存到数据库
+ (HJChatMessageModel *)transferNoticeMessageModelWithDict:(NSDictionary *)dict {
    
    NSDictionary *msg = dict[@"msg"];
    NSDictionary *payInfo = [msg[@"content"] mj_JSONObject];
    HJChatMessageModel *messageModel = [[HJChatMessageModel alloc] init];
    messageModel.serverMsgId = toString(dict[@"seq_id"]);
    messageModel.timestamp = toString(dict[@"send_time_srv"]);
    messageModel.sessionId = toString(dict[@"session_id"]);
    messageModel.orderStatus = [payInfo[@"order_status"] integerValue];
    if ([payInfo isKindOfClass:NSDictionary.class]) {
        messageModel.msgId = toString(payInfo[@"msg_id"]);
    } else {
        messageModel.msgId = toString(dict[@"association_msg_id"]);
    }
    messageModel.systemMsgType = HJChatSystemMsgTypeTransfer;
    messageModel.msgStatus = HJMessageStatusSucceed;
    messageModel.chatType = HJChatTypeSingle;
    messageModel.messageType = HJMessageTypeTransfer;
    return messageModel;
}

+ (HJChatMessageModel *)transferMessageModelWithDict:(NSDictionary *)dict {
    HJChatMessageModel *messageModel = [HJChatMessageModel chatMessageModelWithDict:dict];
    NSDictionary *msg = dict[@"msg"];
    NSDictionary *payInfo = [msg[@"content"] mj_JSONObject];
    messageModel.orderStatus = [payInfo[@"order_status"] integerValue];
    messageModel.orderType = [payInfo[@"order_type"] integerValue];
    messageModel.orderId = toString(payInfo[@"order_id"]);
    messageModel.payCoin = payInfo[@"pay_coin"];
    messageModel.amount = toString(payInfo[@"value"]);
    messageModel.content = @"[Transfer]";
    if ([msg isKindOfClass:NSDictionary.class]) {
        messageModel.msg = @{
            @"content": payInfo
        }.mj_JSONString;
    }
    return messageModel;
}


+ (HJChatMessageModel *)textMessageModelWithDict:(NSDictionary *)dict {
    HJChatMessageModel *messageModel = [HJChatMessageModel chatMessageModelWithDict:dict];
    NSDictionary *msgDict = dict[@"msg"];
    if ([msgDict isKindOfClass:NSDictionary.class]) {
        messageModel.content = msgDict[@"content"];
        messageModel.msg = [dict[@"msg"] mj_JSONString];
    }
    return messageModel;
}

+ (HJChatMessageModel *)imageMessageModelWithDict:(NSDictionary *)dict {
    HJChatMessageModel *messageModel = [HJChatMessageModel chatMessageModelWithDict:dict];
    NSDictionary *picture = dict[@"picture"];
    if ([picture isKindOfClass:NSDictionary.class]) {
        messageModel.msg = @"";
        messageModel.fileUrl = picture[@"origin_picture"];
        messageModel.thumbnailUrl = picture[@"url"];
    }
    return messageModel;
}

+ (HJChatMessageModel *)voiceMessageModelWithDict:(NSDictionary *)dict {
    HJChatMessageModel *messageModel = [HJChatMessageModel chatMessageModelWithDict:dict];
    NSDictionary *voice = dict[@"voice"];
    if ([voice isKindOfClass:NSDictionary.class]) {
        messageModel.msg = @{
            @"duration": voice[@"duration"],
            @"fileSize": voice[@"file_size"]
        }.mj_JSONString;
        messageModel.fileUrl = voice[@"url"];
        if (isEmptyString(messageModel.fileUrl)) {
            NSDictionary *msgDict = dict[@"msg"];
            if ([msgDict isKindOfClass:NSDictionary.class]) {
                messageModel.fileUrl = msgDict[@"content"];
            }
        }
    }
    return messageModel;
}

+ (HJChatMessageModel *)videoMessageModelWithDict:(NSDictionary *)dict {
    HJChatMessageModel *messageModel = [HJChatMessageModel chatMessageModelWithDict:dict];
    NSDictionary *video = dict[@"video"];
    if ([video isKindOfClass:NSDictionary.class]) {
        messageModel.msg = @{
            @"duration": video[@"duration"],
            @"fileSize": video[@"file_size"]
        }.mj_JSONString;
        messageModel.fileUrl = video[@"url"];
        messageModel.thumbnailUrl = video[@"cover"];
        if (isEmptyString(messageModel.fileUrl)) {
            NSDictionary *msgDict = dict[@"msg"];
            if ([msgDict isKindOfClass:NSDictionary.class]) {
                messageModel.fileUrl = msgDict[@"content"];
            }
        }
    }
    return messageModel;
}

//聊天的消息
+ (HJChatMessageModel *)chatMessageModelWithDict:(NSDictionary *)dict {
    HJChatMessageModel *messageModel = [HJChatMessageModel baseMessageModelWithDict:dict];
    if (messageModel.chatType == HJChatTypeSingle || messageModel.chatType == HJChatTypeGroup) {
        messageModel.senderId = toString(dict[@"send_uid"]);
        messageModel.sessionId = toString(dict[@"session_id"]);
        
        if (messageModel.chatType == HJChatTypeSingle) {
            messageModel.receiverId = toString(dict[@"rcv_uid"]);
        } else {
            messageModel.groupId = toString(dict[@"session_id"]);
        }
                
        messageModel.senderNickname = dict[@"sender_name"];
        messageModel.senderAvatar = dict[@"sender_pic"];
    }
    return messageModel;
}

+ (HJChatMessageModel *)baseMessageModelWithDict:(NSDictionary *)dict {
    
    HJChatMessageModel *messageModel = [[HJChatMessageModel alloc] init];
    messageModel.serverMsgId = toString(dict[@"seq_id"]);
    messageModel.msgId = messageModel.serverMsgId;
    messageModel.msgStatus = HJMessageStatusSucceed;
    
    NSInteger chat_type = [dict[@"chat_type"] intValue];
    if (chat_type == HJChatTypeOfficial) {//系统公众号
        messageModel.chatType = HJChatTypeOfficial;
    } else {
        messageModel.chatType = [dict[@"op"] intValue];
    }
    messageModel.timestamp = toString(dict[@"send_time_srv"]);
    NSInteger type = [dict[@"typ"] intValue];
    messageModel.messageType = type == 50 ? HJMessageTypeSystem : type;
    return messageModel;
}

- (nullable NSAttributedString *)getTipMessageWithDict:(NSDictionary *)msgDict {
    if (_chatType == HJChatTypeSingle) {
        return [self getSingleChatTipMessageWithDict:msgDict];
    }
    
    if (_chatType == HJChatTypeGroup) {
        return [self getGroupChatTipMessageWithDict:msgDict];
    }
    return nil;
}

- (nullable NSAttributedString *)getSingleChatTipMessageWithDict:(NSDictionary *)msgDict {
    if (!msgDict) return nil;
    if (_systemMsgType == 2) {//申请好友通过
        self.content = msgDict[@"content"];
        return [self.content attributedStringWithRangeString:nil rangeColor:UIColor.tj_868391Color color:UIColor.tj_BEBDCAColor];
    }
    
    self.content = msgDict[@"content"];
    return [self.content attributedStringWithRangeString:nil rangeColor:UIColor.tj_868391Color color:UIColor.tj_BEBDCAColor];
}

- (nullable NSString *)getNamesWithDict:(NSDictionary *)systemMsgDict {
    NSArray *be_executed = systemMsgDict[@"be_executed"];
    if (![be_executed isKindOfClass:NSArray.class]) {
        return nil;
    }
    NSMutableArray *names = [NSMutableArray arrayWithCapacity:be_executed.count];
    for (NSDictionary *dict in be_executed) {
        [names addObject:dict[@"name"]];
    }
    return [names componentsJoinedByString:@"."];
}

- (nullable NSAttributedString *)getGroupChatTipMessageWithDict:(NSDictionary *)systemMsgDict {
    
    if (!systemMsgDict) return nil;
    
    NSString *operator = systemMsgDict[@"operator"][@"name"];
    NSString *operatorUserId = toString(systemMsgDict[@"operator"][@"user_id"]);

    if (_systemMsgType == HJChatSystemMsgTypeDisbandGroup) {//解散群
        return nil;
    }
    
    if (_systemMsgType == HJChatSystemMsgTypeTransferGroup) {//转让群
        NSArray *be_executed = systemMsgDict[@"be_executed"];
        if (![be_executed isKindOfClass:NSArray.class]) {
            return nil;
        }
        
        NSDictionary *userDict = be_executed.firstObject;
        
        self.content = [NSString stringWithFormat:@"%@ New group owner", userDict[@"name"]];
        NSMutableAttributedString *contentAttributedString = [self.content attributedStringWithRangeString:userDict[@"name"] rangeColor:UIColor.tj_868391Color color:UIColor.tj_BEBDCAColor];
        [contentAttributedString addAttribute:NSFontAttributeName value:UIFontMake(12) range:NSMakeRange(0, contentAttributedString.length)];
        return contentAttributedString;
    }
    
    if (_systemMsgType == HJChatSystemMsgTypeNewGroup) {//新建群
        
        NSString *names = [self getNamesWithDict:systemMsgDict];
        if (!names) return nil;
        
        self.content = [NSString stringWithFormat:@"%@ invited %@ to join the group", TJIM_isSelf(operatorUserId) ? @"You" : operator, names];
        NSMutableAttributedString *contentAttributedString = [self.content attributedStringWithRangeString:names rangeColor:UIColor.tj_868391Color color:UIColor.tj_BEBDCAColor];
        [contentAttributedString addAttribute:NSFontAttributeName value:UIFontMake(12) range:NSMakeRange(0, contentAttributedString.length)];
        return contentAttributedString;
    }
    
    if (_systemMsgType == HJChatSystemMsgTypeJoinGroup) {//邀请入群
        
        NSString *names = [self getNamesWithDict:systemMsgDict];
        if (!names) return nil;
        
        if ([operator isEqualToString:names]) {
            if (TJIM_isSelf(operatorUserId)) {
                names = @"You";
            }
            self.content = [NSString stringWithFormat:@"%@ joined the group", names];
        } else {
            self.content = [NSString stringWithFormat:@"%@ invited %@ to join the group", TJIM_isSelf(operatorUserId) ? @"You" : operator, names];
        }
        NSMutableAttributedString *contentAttributedString = [self.content attributedStringWithRangeString:names rangeColor:UIColor.tj_868391Color color:UIColor.tj_BEBDCAColor];
        [contentAttributedString addAttribute:NSFontAttributeName value:UIFontMake(12) range:NSMakeRange(0, contentAttributedString.length)];
        return contentAttributedString;
    }
    
    if (_systemMsgType == HJChatSystemMsgTypeShareJoinGroup) {//分享入群
        
        NSString *names = [self getNamesWithDict:systemMsgDict];
        if (!names) return nil;
        
        if (TJIM_isSelf(operatorUserId)) {
            names = @"You";
        }
        
        self.content = [NSString stringWithFormat:@"%@ joined the group", names];
        NSMutableAttributedString *contentAttributedString = [self.content attributedStringWithRangeString:names rangeColor:UIColor.tj_868391Color color:UIColor.tj_BEBDCAColor];
        [contentAttributedString addAttribute:NSFontAttributeName value:UIFontMake(12) range:NSMakeRange(0, contentAttributedString.length)];
        return contentAttributedString;
    }
    
    if (_systemMsgType == HJChatSystemMsgTypeModifyGroupName) {//修改了群名字
        self.content = [NSString stringWithFormat:@"%@ modified group name to：%@", operator, systemMsgDict[@"new_room_name"]];
        NSMutableAttributedString *contentAttributedString = [self.content attributedStringWithRangeStrings:@[operator, systemMsgDict[@"new_room_name"]] rangeColor:UIColor.tj_868391Color color:UIColor.tj_BEBDCAColor];
        [contentAttributedString addAttribute:NSFontAttributeName value:UIFontMake(12) range:NSMakeRange(0, contentAttributedString.length)];
        return contentAttributedString;
    }
    
    if (_systemMsgType == HJChatSystemMsgTypeAddGroupManager) {//添加群管理员
        
        NSString *names = [self getNamesWithDict:systemMsgDict];
        if (!names) return nil;
        
        self.content = [NSString stringWithFormat:@"The group owner sets the %@ as administrator",names];
        NSMutableAttributedString *contentAttributedString = [self.content attributedStringWithRangeString:names rangeColor:UIColor.tj_868391Color color:UIColor.tj_BEBDCAColor];
        [contentAttributedString addAttribute:NSFontAttributeName value:UIFontMake(12) range:NSMakeRange(0, contentAttributedString.length)];
        return contentAttributedString;
    }
    
    if (_systemMsgType == HJChatSystemMsgTypeRemoveGroupManager) {//删除群管理员
        
        NSString *names = [self getNamesWithDict:systemMsgDict];
        if (!names) return nil;

        self.content = [NSString stringWithFormat:@"The group owner cancels the %@ administrator status",names];
        NSMutableAttributedString *contentAttributedString = [self.content attributedStringWithRangeString:names rangeColor:UIColor.tj_868391Color color:UIColor.tj_BEBDCAColor];
        [contentAttributedString addAttribute:NSFontAttributeName value:UIFontMake(12) range:NSMakeRange(0, contentAttributedString.length)];
        return contentAttributedString;
    }
    
    if (_systemMsgType == HJChatSystemMsgTypeKickOutGroup) {//被踢退群
        
        NSString *names = [self getNamesWithDict:systemMsgDict];
        if (!names) return nil;
        
        if (![operatorUserId isEqualToString:HJUserInfo.userId]) {//被踢人只有操作者能看见
            return nil;
        };

        self.content = [NSString stringWithFormat:@"%@ Left the group", names];
        NSMutableAttributedString *contentAttributedString = [self.content attributedStringWithRangeString:names rangeColor:UIColor.tj_868391Color color:UIColor.tj_BEBDCAColor];
        [contentAttributedString addAttribute:NSFontAttributeName value:UIFontMake(12) range:NSMakeRange(0, contentAttributedString.length)];
        return contentAttributedString;
    }
    
    if (_systemMsgType == HJChatSystemMsgTypeLeaveGroup) {//退群
        self.content = [NSString stringWithFormat:@"%@ Left the group", operator];
        NSMutableAttributedString *contentAttributedString = [self.content attributedStringWithRangeString:operator rangeColor:UIColor.tj_868391Color color:UIColor.tj_BEBDCAColor];
        [contentAttributedString addAttribute:NSFontAttributeName value:UIFontMake(12) range:NSMakeRange(0, contentAttributedString.length)];
        return contentAttributedString;
    }
    
    if (_systemMsgType == HJChatSystemMsgTypePostGroupNotice) {//发布群公告
        self.content = systemMsgDict[@"notice_content"];
        NSMutableAttributedString *contentAttributedString = [self.content attributedStringWithRangeString:nil rangeColor:UIColor.tj_868391Color color:UIColor.tj_BEBDCAColor];
        [contentAttributedString addAttribute:NSFontAttributeName value:UIFontMake(12) range:NSMakeRange(0, contentAttributedString.length)];
        return contentAttributedString;
    }
    
    if (_systemMsgType == HJChatSystemMsgTypeApplyJoinGroup) {//审核通知
        return nil;
    }
    return nil;
}


+ (HJChatMessageModel *)tipMessageModelWithDict:(NSDictionary *)dict {

    HJChatMessageModel *messageModel = [HJChatMessageModel chatMessageModelWithDict:dict];
    messageModel.systemMsgType = [dict[@"system_msg_typ"] intValue];
    NSDictionary *systemMsgDict = dict[@"room_sys_msg"];
    
    if (messageModel.chatType == HJChatTypeSingle) {
        [messageModel getSingleChatTipMessageWithDict:dict[@"msg"]];
        if (messageModel.content) {
            messageModel.msg = [dict[@"msg"] mj_JSONString];
        }
    } else if (messageModel.chatType == HJChatTypeGroup) {
        [messageModel getGroupChatTipMessageWithDict:systemMsgDict];
        if (messageModel.content) {
            messageModel.msg = [systemMsgDict mj_JSONString];
        }
        if (messageModel.systemMsgType == HJChatSystemMsgTypePostGroupNotice) {
            messageModel.messageType = HJMessageTypeNotice;
        }
    }
    return messageModel;
}

+ (nullable HJChatMessageModel *)messageModelWithDict:(NSDictionary *)dict {
    
    NSInteger chat_type = [dict[@"chat_type"] intValue];
    NSInteger session_id = [dict[@"session_id"] integerValue];
    NSInteger messageType = [dict[@"typ"] intValue];

    if (chat_type == HJChatTypeOfficial) {
        
        if (session_id == KaiPaySessionId) {
            return [self payMessageModelWithDict:dict];
        }
        
        if (session_id == KaiNewsSessionId) {
            return [self newsMessageModelWithDict:dict];
        }
    } else {
        
        NSInteger system_msg_typ = [dict[@"system_msg_typ"] intValue];
        if (system_msg_typ == HJChatSystemMsgTypeTransfer){
            return [HJChatMessageModel transferNoticeMessageModelWithDict:dict];
        }
        
        if (messageType == HJMessageTypeTransfer){
            return [HJChatMessageModel transferMessageModelWithDict:dict];
        }

        if (messageType == HJMessageTypeText) {
            return [HJChatMessageModel textMessageModelWithDict:dict];
        }
        
        if (messageType == HJMessageTypeImage) {
            return [HJChatMessageModel imageMessageModelWithDict:dict];
        }
        
        if (messageType == HJMessageTypeVoice) {
            return [HJChatMessageModel voiceMessageModelWithDict:dict];
        }
        
        if (messageType == HJMessageTypeVideo) {
            return [HJChatMessageModel videoMessageModelWithDict:dict];
        }
        
        if (messageType == HJMessageTypeSystem  || messageType == HJMessageTypeOtherSystem) {
            return [HJChatMessageModel tipMessageModelWithDict:dict];
        }
    }
    return nil;
}

//data = (
//{
//is_top = 0;
//session_image = https://img-fs-dev.s3.ap-southeast-1.amazonaws.com/upload/profile_picture/75820004-avatar-3.png;
//session_name = 3zFKdfbt;
//session_id = 507968536178949;
//user_id = 478014916317381;
//is_mute = 0;
//chat_type = 1;
//msgs = (
//{
//session_id = 507968536178949;
//status = 0;
//user_id = 478014916317381;
//duration = 0;
//send_at = 1706154400058;
//updated_at = 1706154400059;
//burn_duration = 0;
//original_picture = ;
//sender_pic = https://img-fs-dev.s3.ap-southeast-1.amazonaws.com/upload/profile_picture/75820004-avatar-3.png;
//seq_id = 507977720049925;
//type = 91;
//chat_type = 1;
//is_burn = 0;
//transfer_state = 0;
//sender_name = 3zFKdfbt;
//sys_msg_type = 0;
//client_msg_id = 0;
//created_at = 1706154400059;
//other_user_id = 472996269219909;
//association_msg_id = 507977718169861;
//content = {"id":74757,"created_at":1706154399,"updated_at":1706154399,"deleted_at":0,"order_id":"ff8787e6e08bcb99a208435ed67b88f1","no":"17061543993024780149163173815166","out_trade_order_id":"M20240125114639405569061263507461","create_by":478014916317381,"order_status":3,"code":0,"title":"Transfer","describe":"{\"from\":\"3zFKdfbt\",\"fromUid\":478014916317381,\"to\":\"tt555555\",\"toUid\":472996269219909}","from":110464807429304320,"to":105325712801624064,"pay_type":1,"pay_coin":"USDT","value":"3000000","internal_fee":"0","tripartite_fee":"0","order_type":1,"session_id":507968536178949,"msg_id":507977718169861,"association_id":""};
//file_size = 0;
//}

+ (nullable HJChatMessageModel *)messageModelWithSessionDict:(NSDictionary *)sessionDict messageDict:(NSDictionary *)dict {
    
    NSInteger systemMsgType = [dict[@"sys_msg_type"] intValue];
    NSInteger type = [dict[@"type"] intValue];
    NSInteger chat_type = [dict[@"chat_type"] intValue];
    
    if (systemMsgType == 31){
        return nil;
    }
    
    HJMessageType messageType = type == 50 ? HJMessageTypeSystem : type;
    BOOL showTips = chat_type == 1 || chat_type == 2;
    if (messageType == HJMessageTypeSystem && !showTips) {//不需要显示的直接过滤
        return nil;
    }
    
    HJChatMessageModel *messageModel = [[HJChatMessageModel alloc] init];
    messageModel.serverMsgId = toString(dict[@"seq_id"]);
    messageModel.sessionId = toString(dict[@"session_id"]);
    messageModel.senderId = toString(dict[@"user_id"]);
    
    messageModel.msgId = messageModel.serverMsgId;
    messageModel.msgStatus = HJMessageStatusSucceed;
    messageModel.messageType = messageType;
    messageModel.timestamp = toString(dict[@"created_at"]);
    messageModel.systemMsgType = systemMsgType;
    

    if (chat_type == 1) {
        
        messageModel.chatType = HJChatTypeSingle;
        messageModel.receiverId = toString(dict[@"other_user_id"]);
        messageModel.senderAvatar = sessionDict[@"session_image"];

        if (messageType == HJMessageTypeTransfer) {
            
            NSDictionary *payInfo = [dict[@"content"] mj_JSONObject];
            messageModel.orderStatus = [payInfo[@"order_status"] integerValue];
            messageModel.orderType = [payInfo[@"order_type"] integerValue];
            messageModel.orderId = toString(payInfo[@"order_id"]);
            messageModel.payCoin = payInfo[@"pay_coin"];
            messageModel.amount = toString(payInfo[@"value"]);
            
            if (!TJIM_isSelf(messageModel.senderId)) {
                messageModel.sessionUserd = messageModel.senderId;
            }
            
            messageModel.content = @"[Transfer]";
            messageModel.msg = [@{
                @"content": payInfo
            } mj_JSONString];
        } else {
            messageModel.sessionUserd = messageModel.senderId;
        }
        
    } else if (chat_type == 2) {
        
        messageModel.chatType = HJChatTypeGroup;
        messageModel.groupId = toString(dict[@"session_id"]);
        messageModel.senderNickname = dict[@"sender_name"];
        messageModel.senderAvatar = dict[@"sender_pic"];
        
    } else if (chat_type == 3) {
        
        messageModel.chatType = HJChatTypeOfficial;
        messageModel.sessionId = getOfficiaSessionId(dict[@"session_id"]);
        messageModel.senderNickname = dict[@"sender_name"];
        messageModel.senderAvatar = dict[@"sender_pic"];
        messageModel.sessionName = sessionDict[@"session_name"];
        messageModel.sessionAvatar = sessionDict[@"session_image"];
        messageModel.associationmMsgId = toString(dict[@"association_msg_id"]);

        NSInteger Id = [dict[@"session_id"] integerValue];
        if (Id == 0) return nil;

        if (Id == KaiPaySessionId) {
            messageModel.officialType = HJChatOfficialTypeKaiPay;
        } else if (Id == KaiNewsSessionId) {
            messageModel.officialType = HJChatOfficialTypeKaiNews;
        } else if (Id == KaiSupportSessionId) {
            messageModel.officialType = HJChatOfficialTypeKaiSupport;
        }
        
        NSDictionary *contentDict = [dict[@"content"] mj_JSONObject];
        messageModel.content = contentDict[@"title"];
        messageModel.msg = [@{
            @"content": contentDict
        } mj_JSONString];
        
        return messageModel;
    }
    
    if (messageModel.messageType == HJMessageTypeText) {
        messageModel.content = dict[@"content"];
        if (dict[@"content"]) {
            messageModel.msg = [@{
                @"content": dict[@"content"]
            } mj_JSONString];
        }
        return messageModel;
    }
    
    if (messageModel.messageType == HJMessageTypeImage) {
        messageModel.thumbnailUrl = dict[@"content"];
        messageModel.fileUrl = dict[@"original_picture"];
        return messageModel;
    }
    
    if (messageModel.messageType == HJMessageTypeVoice || messageModel.messageType == HJMessageTypeVideo) {
        NSMutableDictionary *msg = [NSMutableDictionary dictionary];
        [msg setValue:dict[@"duration"] forKey:@"duration"];
        [msg setValue:dict[@"file_size"] forKey:@"fileSize"];
        messageModel.thumbnailUrl = dict[@"original_picture"];
        messageModel.msg = msg.mj_JSONString;
        messageModel.fileUrl = dict[@"content"];
        return messageModel;
    }
    
    if (messageModel.messageType == HJMessageTypeSystem) {//拼成在线消息
        if (messageModel.chatType == HJChatTypeSingle) {
            NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
            [dictionary setValue:dict[@"content"] forKey:@"content"];
            [messageModel getSingleChatTipMessageWithDict:dictionary];
            if (messageModel.content) {
                messageModel.msg = [dictionary mj_JSONString];
            }
        } else {
            [messageModel getGroupChatTipMessageWithDict:[dict[@"content"] mj_JSONObject]];
            if (messageModel.content) {
                messageModel.msg = dict[@"content"];
            }
        }
        
        if (messageModel.systemMsgType == HJChatSystemMsgTypePostGroupNotice) {
            messageModel.messageType = HJMessageTypeNotice;
        }
    }
    return messageModel;
}

- (void)downloadVoice {
    if (self.messageType == HJMessageTypeVoice) {
        
        self.localPath = [HJMessageFileManager audiofileFilePathWithSessionId:self.sessionId fileName:self.fileUrl.lastPathComponent];
        if (![[NSFileManager defaultManager] fileExistsAtPath:self.localPath]) {
            HJDownloadFileWithUrl(self.fileUrl, ^(CGFloat value) {
            }, ^NSURL * _Nonnull{
                NSLog(@"下载语音完成");
                return [NSURL fileURLWithPath:self.localPath];
            }, ^(NSError * _Nullable error) {
            });
        }
    }
}

- (NSString *)getMessgetContent {
    if (_messageType == HJMessageTypeText) return self.content;
    if (_messageType == HJMessageTypeImage) return @"[Image]";
    if (_messageType == HJMessageTypeVideo) return @"[Video]";
    if (_messageType == HJMessageTypeVoice) return @"[Voice]";
    if (_messageType == HJMessageTypeOther) return @"[File]";
    return @"";
    
}

- (NSString *)sessionId {
    if (!_sessionId) {
        _sessionId = _groupId;
    }
    return _sessionId;
}

- (BOOL)countedUnreadCount {
    if (_messageType != HJMessageTypeSystem) {
        return YES;
    } else {
        if (_chatType == HJChatTypeOfficial) {
            return YES;
        }
        if (_systemMsgType == HJChatSystemMsgTypePostGroupNotice || _systemMsgType == HJChatSystemMsgTypeApplyFridendAgree) {
            return YES;
        }
    }
    return NO;
}

- (void)previewLink {
    
    if ((self.chatType == HJChatTypeSingle || self.chatType == HJChatTypeGroup) && self.messageType == HJMessageTypeText) {
        
        if (self.linkPreviewInfo) {
            return;
        }
        
        //检查是否是链接
        NSError *error = nil;
        NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:&error];
        NSArray<NSTextCheckingResult *> *matches = [detector matchesInString:self.content options:0 range:NSMakeRange(0, self.content.length)];

        if (matches.count) {
            NSMutableArray *links = [NSMutableArray array];
            for (NSTextCheckingResult *match in matches) {
                if ([match resultType] == NSTextCheckingTypeLink) {
                    [links addObject:match.URL.absoluteString];
                }
            }
            
            //进行解析
            if (links.count) {
                [HJWebsiteFillter websiteMeta:links.firstObject completeHandler:^(NSString * _Nonnull url, NSDictionary * _Nonnull data, NSInteger loadType, NSError * _Nonnull error) {
                    if (data) {
                        self.linkPreviewInfo = data.mj_JSONString;
                        [self bg_saveOrUpdateAsync:^(BOOL isSuccess) {}];
                        dispatch_async_main_queue(^{
                            [[NSNotificationCenter defaultCenter] postNotificationName:loadLinkInfoCompleteNotification object:@{
                                @"message": self,
                                @"url": url,
                                @"data": data,
                                @"loadType": @(loadType)
                            }];
                        });
                    }
                }];
            }
        }
    }
}



@end

